#include "Precomp.h"
#include "Editor.h"

Editor::Editor()
{
}

Editor::~Editor()
{
}

bool Editor::connect(const char *host, unsigned short port)
{
	sf::IPAddress ip=host;
	connection.SetBlocking(true);
	sf::Socket::Status status=connection.Connect(port,ip,10.0f);
	connection.SetBlocking(false);
	root=SquirrelVM::GetRootTable();
	return (status==sf::Socket::Done);
}

void Editor::update()
{
	connection.Receive(packet);
	if(packet.GetDataSize())
	{
		sf::Uint8 cmdtype;
		sf::Uint16 id;
		packet>>cmdtype;
		cmdtype=(CommandType)cmdtype;
		switch(cmdtype)
		{
		case AssignScript:
			packet>>id;
			packet>>script;
			functions[id]=root.GetValue(script.c_str());
		break;
		case RunScriptByID:
			packet>>id;
			SquirrelVM::RunScript(functions[id]);
		break;
		case RunScript:
			packet>>script;
			SquirrelVM::RunScript(SquirrelVM::CompileBuffer(script.c_str()));
		break;
		}
	}
}

void Editor::sendEvent(sf::Event& ev)
{
	packet.Clear();
	sf::Uint8 eventType=EventMessage;
	packet<<eventType;
	packet.Append(&ev,sizeof(ev));
	connection.Send(packet);
}